package com.corner.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.corner.R;
import com.corner.app.ConsTants;
import com.corner.app.GlobalParams;
import com.corner.model.cornerservice.domain.User;
import com.corner.presenter.imp.UserSettingPresenter;
import com.corner.ui.adapter.UserSettingAdapter;
import com.corner.ui.base.BaseActivity;
import com.corner.ui.view.IUserSettingView;
import com.corner.utils.AppManager;
import com.corner.utils.DialogUtil;
import com.corner.utils.IntentUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.TypeFaceUtil;
import com.corner.utils.view.FindView;
import com.corner.utils.view.MainActionBar;
import com.corner.utils.view.widget.XListView;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.IOException;

/**
 * Created by Administrator on 2015/5/23.
 */
public class UserSettingActivity extends BaseActivity<UserSettingPresenter> implements OnClickListener, IUserSettingView {
    public static final int PIC = 1;
    public static final int CAMERA = 2;
    public static final int SELECT_PIC_RECT = 3;
    Dialog selectAvater;
    @FindView(R.id.lv_user_setting)
    private XListView lvUserSetting;
    private LinearLayout header;
    private TextView tvUserName;
    private TextView tvPhoneNum;
    private SimpleDraweeView ivAvater;
    private UserSettingAdapter adapter;
    private TextView tvHeaderDivider;
    private MainActionBar actionBar;
    private TextView tvPics;
    private TextView tvCamera;
    private TextView tvCancel;
    private int currRequestCode;
    private String cameraPicPath;

    @Override
    protected UserSettingPresenter createP() {
        return new UserSettingPresenter();
    }

    @Override
    protected void setOnClick() {
        actionBar.btnLeft.setOnClickListener(this);
        ivAvater.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        lvUserSetting.addHeaderView(header);
        lvUserSetting.addHeaderView(tvHeaderDivider);

        adapter = new UserSettingAdapter(this);
        lvUserSetting.setAdapter(adapter);
        refresh();
    }

    public void refresh() {
        presenter.requestUser();
    }


    @Override
    public void initView() {
        super.initView();
        header = new LinearLayout(this);
        header.setOrientation(LinearLayout.HORIZONTAL);
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, GlobalParams.screenHeight / 5);
        header.setLayoutParams(layoutParams);
        header.setBackgroundColor(getResources().getColor(R.color.white));

        FrameLayout imgOut = (FrameLayout) View.inflate(this, R.layout.user_setting_header_left, null);
        FrameLayout.LayoutParams imgOutPamas = new FrameLayout.LayoutParams(layoutParams.height, layoutParams.height);
        imgOut.setLayoutParams(imgOutPamas);
        ivAvater = (SimpleDraweeView) imgOut.findViewById(R.id.iv_user_setting_header_avater);

        header.addView(imgOut);

        LinearLayout headRight = (LinearLayout) View.inflate(this, R.layout.user_setting_header_right, null);
        tvUserName = (TextView) headRight.findViewById(R.id.tv_user_setting_username);
        tvPhoneNum = (TextView) headRight.findViewById(R.id.tv_user_setting_phone_number);
        TypeFaceUtil.setTypeFace(this, tvUserName, ConsTants.TYPE_FACE);
        TypeFaceUtil.setTypeFace(this, tvPhoneNum, ConsTants.TYPE_FACE);
        LinearLayout.LayoutParams rightPamas = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
        rightPamas.weight = 1;
        headRight.setGravity(Gravity.CENTER_VERTICAL);
        headRight.setLayoutParams(rightPamas);
        header.addView(headRight);

        tvHeaderDivider = new TextView(this);
        AbsListView.LayoutParams dividerParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.dimen_user_setting_header_divider_heaight));
        tvHeaderDivider.setLayoutParams(dividerParams);
        tvHeaderDivider.setBackgroundColor(getResources().getColor(R.color.lv_setting_bg_color));

        actionBar = new MainActionBar(this);
        actionBar.initActionBarButton();
        actionBar.btnLeft.setVisibility(View.VISIBLE);
        actionBar.btnLeft.setText(getString(R.string.user_setting_action_bar_left));

        lvUserSetting.setAutoLoadEnable(false);
        lvUserSetting.setPullLoadEnable(false);
        lvUserSetting.setPullRefreshEnable(false);
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_user_setting);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_actionbar_left:
                AppManager.getInstance().finishActivity(this);
                break;
            case R.id.iv_user_setting_header_avater:
                showSelectAvaterDialog();
                break;
            case R.id.tv_user_setting_dialog_select_avater_pics:
                DialogUtil.hideDialog(selectAvater);
                // 拿照片
                Intent intent_file = IntentUtil.getPicIntent();
                this.currRequestCode = PIC;
                startActivityForResult(intent_file, currRequestCode);
                break;
            case R.id.tv_user_setting_dialog_select_avater_camera:
                DialogUtil.hideDialog(selectAvater);
                // 照相
                Intent intent_camera;
                try {
                    cameraPicPath = GlobalParams.APPFIEPATH + "/camera/"
                            + System.currentTimeMillis() + ".jpg";
                    intent_camera = IntentUtil.getCameraIntent(cameraPicPath);
                    this.currRequestCode = CAMERA;
                    startActivityForResult(intent_camera, this.currRequestCode);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tv_user_setting_dialog_select_avater_cancel:
                DialogUtil.hideDialog(selectAvater);
                break;
        }
    }

    private void showSelectAvaterDialog() {
        if (selectAvater == null) {
            selectAvater = DialogUtil.showDiaLog(R.layout.dialog_user_setting_select_avater, this);
            TextView tvTitle = (TextView) selectAvater.findViewById(R.id.tv_user_setting_dialog_select_avater_title);
            TypeFaceUtil.setTypeFace(this, tvTitle, ConsTants.TYPE_FACE);
            tvPics = (TextView) selectAvater.findViewById(R.id.tv_user_setting_dialog_select_avater_pics);
            TypeFaceUtil.setTypeFace(this, tvPics, ConsTants.TYPE_FACE);
            tvPics.setOnClickListener(this);
            tvCamera = (TextView) selectAvater.findViewById(R.id.tv_user_setting_dialog_select_avater_camera);
            TypeFaceUtil.setTypeFace(this, tvCamera, ConsTants.TYPE_FACE);
            tvCamera.setOnClickListener(this);
            tvCancel = (TextView) selectAvater.findViewById(R.id.tv_user_setting_dialog_select_avater_cancel);
            TypeFaceUtil.setTypeFace(this, tvCancel, ConsTants.TYPE_FACE);
            tvCancel.setOnClickListener(this);
        } else {
            selectAvater.show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_PIC_RECT) {
            if (resultCode == SelectPicShowRectActivity.OK) {
                final float[] scales = data
                        .getFloatArrayExtra(SelectPicShowRectActivity.SCALE);
                final String currentPicPath = data
                        .getStringExtra(SelectPicShowRectActivity.PICTUREPATH);
                uploadAvater(scales, currentPicPath);
            }
        } else {
            String picturePath = null;
            if (requestCode == PIC) {
                if (data == null)
                    return;
                Uri selectedImage = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage,
                        filePathColumns, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                picturePath = c.getString(columnIndex);
                c.close();
            } else if ((requestCode == CAMERA)
                    && (resultCode == Activity.RESULT_OK)) {
                picturePath = cameraPicPath;
            }
            if (picturePath != null) {
                Intent intent = new Intent(getApplicationContext(),
                        SelectPicShowRectActivity.class);
                intent.putExtra(SelectPicShowRectActivity.PICTUREPATH,
                        picturePath);
                intent.putExtra(SelectPicShowRectActivity.INTENT_ID,
                        SelectPicShowRectActivity.AVATER);
                startActivityForResult(intent, SELECT_PIC_RECT);
            }
        }
    }

    /**
     * 上传头像
     *
     * @param scales
     * @param currentPicPath
     */
    private void uploadAvater(final float[] scales, final String currentPicPath) {
        excuteTaskWhenNetOk(new Task() {
            @Override
            public void onExcute() {
                presenter.changeAvater(scales, currentPicPath);
            }
        });
    }

    @Override
    public void requestUserSucess(User user) {
        if (user.getAvaterUrl() != null) {
            ivAvater.setImageURI(Uri.parse(user.getAvaterUrl()));
        }
        String nickName = user.getUsername();
        adapter.setNickName(nickName);
        tvUserName.setText(nickName);
        tvPhoneNum.setText(user.getPhoneNum());
    }

    @Override
    public void changeAvaterSucess() {
        ToastUtil.showCustomToastInRelease(UserSettingActivity.this, getString(R.string.user_setting_avater_upload_sucess));
        refresh();
    }

    @Override
    public void changeAvaterError(String message) {
        ToastUtil.showCustomToastInRelease(this, message);
    }
}
